package br.ufrgs.inf.sissw.app;

import java.util.Calendar;
import java.util.Date;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.opengl.Visibility;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import br.ufrgs.inf.sissw.app.models.AgendaItem;

public class AgendaItemCreationActivity extends AbstractDashboardActivity  implements OnClickListener{

	/* these are the item`s attributes */
	private EditText itemTitle;
	private EditText itemDescription;
	private boolean isInEditionMode;
	private AgendaItem newItem;

	/* TimePicker controllers */
	private TextView mTimeDisplay;
	private Button mPickTime;
	private int mHour;
	private int mMinute;
	static final int TIME_DIALOG_ID = 0;

	/* DatePicker controllers */
	private TextView mDateDisplay;
	private Button mPickDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	static final int DATE_DIALOG_ID = 1;

	/* activityController */
	private Button buttonUpdateOrAddItem;
	private Button buttonDeleteItem;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		try {

			itemTitle = (EditText) findViewById(R.id.editTextTitle);
			itemDescription = (EditText) findViewById(R.id.editTextDescription);
			buttonUpdateOrAddItem = (Button) findViewById(R.id.buttonUpdateOrAddItem);
			buttonDeleteItem = (Button) findViewById(R.id.buttonDeleteItem);
			
			buttonUpdateOrAddItem.setOnClickListener(this);
			buttonDeleteItem.setOnClickListener(this);
			
			/* both functions are used to set the time and date popups */
			timePickerControllersSetUp();
			datePickerControllersSetUp();

			/* trying to retrieve a previews item, if null it means we are creating a new item*/
			newItem = (AgendaItem) getIntent().getExtras().get("agendaItem");
			
		} catch (Exception exception) {
			System.out
					.println("Error in AgendaItemCreationActivity.onCreate - trying to load Activity Views");
			System.out.println("Message - " + exception.getMessage());
		}

		if (newItem != null) {

			// initializeScreenWithData();
			isInEditionMode = true;
			itemTitle.setText(newItem.getItemTitle());
			itemDescription.setText(newItem.getItemDescription());

			if (newItem.getItemDate() != null) {
				mHour = newItem.getItemDate().getHours();
				mMinute = newItem.getItemDate().getMinutes();

				mYear = newItem.getItemDate().getYear();
				mMonth = newItem.getItemDate().getMonth();
				mDay = newItem.getItemDate().getDay();

			} else {
				// get the current time
				final Calendar c = Calendar.getInstance();
				mHour = c.get(Calendar.HOUR_OF_DAY);
				mMinute = c.get(Calendar.MINUTE);
				mYear = c.get(Calendar.YEAR);
				mMonth = c.get(Calendar.MONTH);
				mDay = c.get(Calendar.DAY_OF_MONTH);
			}

		} else {

			isInEditionMode = false;
			final Calendar c = Calendar.getInstance();
			mHour = c.get(Calendar.HOUR_OF_DAY);
			mMinute = c.get(Calendar.MINUTE);
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
		}

		// display the current date
		updateDisplay();
		
		if(isInEditionMode) {
			buttonUpdateOrAddItem.setText("Atualizar evento");
		}
		else {
			buttonUpdateOrAddItem.setText("Adicionar evento");	
		}
	}

	private void datePickerControllersSetUp() {

		// capture our View elements
		mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
		mPickDate = (Button) findViewById(R.id.pickDate);

		// add a click listener to the button
		mPickDate.setOnClickListener(this);
	}

	private void timePickerControllersSetUp() {
		// capture our View elements
		mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
		mPickTime = (Button) findViewById(R.id.pickTime);

		// add a click listener to the button
		mPickTime.setOnClickListener(this);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);

		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);

		}

		return null;
	}

	// updates the time we display in the TextView
	private void updateDisplay() {
		mTimeDisplay.setText(new StringBuilder().append("Hora - ")
				.append(dateFormatter(mHour)).append(":")
				.append(dateFormatter(mMinute)));

		mDateDisplay.setText(new StringBuilder().append("Data - ").
				append(dateFormatter(mDay)).append("/")
				.append(dateFormatter(mMonth + 1)).append("/")
				.append(dateFormatter(mYear)).append(" "));

	}

	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplay();
		}
	};

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};
	
	private static String dateFormatter(int c) {
		if (c >= 10 && c < 100)
			return String.valueOf(c);
		else if (c < 10)
			return "0" + String.valueOf(c);
		else return String.valueOf(c);
	}

	@Override
	protected int getContentView() {
		return R.layout.agenda_item_creation_activity;
	}

	@Override
	protected int getFeatureNameResourceId() {
		return R.string.agendaItemCreation;
	}

	public void onClick(View v) {
		int id = v.getId();
		
		switch(id)
		{
			case R.id.pickDate:
				showDialog(DATE_DIALOG_ID);
				break;
			case R.id.pickTime:
				showDialog(TIME_DIALOG_ID);
				break;
			case R.id.buttonUpdateOrAddItem:
				
				if(isInEditionMode) {
					if(itemTitle.getText().length() <= 0) {
						Toast.makeText(this, "Preencha o nome do evento.", Toast.LENGTH_SHORT).show();
					}
					else {
						newItem.setItemTitle(itemTitle.getText().toString());
						newItem.setItemDate(new Date(mYear, mMonth, mDay, mHour, mMinute, 0));
						newItem.setItemDescription(itemDescription.getText().toString());
						Toast.makeText(this, "Evento Atualizado!", Toast.LENGTH_SHORT).show();
					}
				}
				else {
					Toast.makeText(this, "Novo Evento Adicionado!", Toast.LENGTH_SHORT).show();	
				}
				
				 
			case R.id.buttonDeleteItem:
				
				break;

			default:
				break;
				
		}
		
	}

}